import express from 'express'
import fs from 'fs';
import path from 'path';
import multiparty from 'connect-multiparty';
//文件操作模块
import fileAccess from './functions/file-access.mjs'

//定义体重文件地址
const dataFilePath = path.join('.', 'data', 'weight-data.json');
//创建服务器
const app = express();
const port = 18888;
//设置允许跨域请求
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*'); //访问控制允许来源：所有
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); //访问控制允许报头 X-Requested-With: xhr请求
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); //访问控制允许方法
    res.header('X-Powered-By', 'nodejs'); //自定义头信息，表示服务端用nodejs
    // res.header('Content-Type', 'application/json;charset=utf-8');
    next();
});
//响应获取体重数据的请求
app.get('/GetWeightData', ((req, res) => {
    fs.readFile(dataFilePath, 'utf-8', ((err, data) => {
        if (err) {
            throw err;
        } else {
            // console.log(data);
            res.send(data);
        }
    }));
}));

//响应添加体重记录的请求
let multipartyMiddleware = multiparty({});
app.post('/AddNewRecord', multipartyMiddleware, (req, res) => {
    fileAccess.addNewRecord(req.body).then(() => {
        res.send()
    }, () => {
        res.send('error');
    });
});

app.listen(port, () => {
})